<template>
    <div class="operate">
        <template>
            <div class="operate-btn">
                <div class="leftBtn">
                    <!-- <el-button type="primary">新增条目</el-button>
                    <el-button>复制条目</el-button> -->
                    <el-button @click="openRelevancyDialog" :disabled="!indexClauseList.length">添加关联</el-button>
                    <el-button type="danger" @click="delClauseDialog(itemCodes, '批量解除')">解除关联</el-button>
                </div>
                <div class="rightBtn">
                    <el-input
                        v-model="indexClauseRelationParam.entryNameOrCodeLike"
                        size="small"
                        prefix-icon="el-icon-search"
                        placeholder="请输入规则序号、编号或名称"
                        style="width:230px;margin-right:10px"
                        @input="clauseTextLikeQuery"
                    />
                    <el-button-group>
                        <el-button @click="clickRuleQuery">高级查询</el-button>
                        <el-button icon="el-icon-refresh-right" @click="getIndexClauseRelationList(indexClauseRelationParam)"></el-button>
                        <el-button icon="el-icon-upload2" @click="downLoadGroupFileBtn"></el-button>
                        <el-button icon="el-icon-setting" @click="layoutDialog = true"></el-button>
                    </el-button-group>
                </div>
            </div>
            <div style="width: 98%; height:100%; margin: 0 auto; border: 1px solid #d7d7d7;">
                <vxe-table
                    ref="upstreamTable"
                    :key="tableKey"
                    :data="indexClauseRelationList"
                    border
                    size="mini"
                    style="width: 100%"
                    max-height="220px"
                    header-align="center"
                    show-overflow
                    @filter-change="filterChangeEvent"
                    @checkbox-change="clauseChangeEvent"
                    @checkbox-all="clauseChangeEvent"
                >
                    <vxe-column type="checkbox" width="50" fixed="left" align="center"></vxe-column>
                    <vxe-column
                        v-for="(item) in showFieldList"
                        :key="item.clauseNo"
                        :field="item.id"
                        :title="item.content"
                        :sortable="item.sortable"
                        :width="item.width"
                        min-width="120"
                        :filters="item.filters"
                        :filter-method="filterHandler"
                    >
                        <template #filter="{ $panel, column }" v-if="['entryName'].includes(item.id)">
                            <el-input
                                class="my-input"
                                type="type"
                                v-for="(option, index) in column.filters"
                                :key="index"
                                v-model="option.data"
                                @input="$panel.changeOption($event, !!option.data, option)"
                            />
                        </template>
                        <template slot-scope="scope">
                            <!-- <span v-if="['modifyTime'].includes(item.id)">{{timeFormat(scope.row.modifyTime) || '--'}}</span> -->
                            <span v-if="['thresholdValue1', 'thresholdValue2', 'thresholdValue3'].includes(item.id)">
                                {{ scope.row[item.id] ? thresholdTypeFormat(scope.row[item.id], scope.row.unit) : '' }}
                            </span>
                            <span v-else v-html="getTablesData(scope.row, item.id)"></span>
                        </template>
                    </vxe-column>
                    <vxe-column title="操作" width="65">
                        <template slot-scope="scope">
                            <RiskIconButton
                                type="danger"
                                icon="el-icon-circle-close"
                                topTitle="解除关联"
                                v-authCode="B_0191"
                                @on-click="delClauseDialog(scope.row, '单个解除')"
                            ></RiskIconButton>
                        </template>
                    </vxe-column>
                </vxe-table>    
            </div>    
        </template>
        <template>
            <!-- 复制条目 -->
            <CopyEntryDialog
                :copyEntryDialog="copyEntryDialog"
                :indexClauseRelation="indexClauseRelation"
                :clauseCodesList="clauseCodesList"
                @emitCopyEntryDialog="emitCopyEntryDialog"
            ></CopyEntryDialog>
            <!-- 规则高级查询 -->
            <RuleQueryDialog
                :ruleQueryDialog="ruleQueryDialog"
                @emitRuleQuery="emitRuleQuery"
                @emitConfirmQuery="emitConfirmQuery"
            ></RuleQueryDialog>
            <!-- 解除关联确认窗口 -->
            <DeletionConfirmationDialog
                :delConfirmationDialog="delConfirmationDialog"
                @emitDialogVisible="emitDialogVisible"
                @emitHandleBtn="emitHandleBtn"
            >
                <div slot="content1">{{delContent}}</div>
            </DeletionConfirmationDialog>
            <RiskTableLayout
                title="页面布局"
                :visible.sync="layoutDialog"
                :field-list="tableColumns"
                :selected-field-list="selectedFieldList"
                :fixed-field-list="fixedFieldList"
                table-name="COMPLIANCE_RULES"
                @on-submit="onSubmit"
            />
        </template>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import CopyEntryDialog from './components/copy-entry-dialog.vue'
import RuleQueryDialog from './components/rule-query-dialog.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import DeletionConfirmationDialog from './commom/deletion-confirmation-dialog.vue'
import { timeFormat, numberFormat, unitShow } from '@/utils/tools';
import { downLoadFile } from '@/utils/request';
import { getTableLayout } from '@/common/api/commonApi';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import Invest from '@/common/dict/invest';
@Component({
    name: 'ComplianceRules',
    components: {
        RiskIconButton,
        CopyEntryDialog,
        RuleQueryDialog,
        RiskTableLayout,
        DeletionConfirmationDialog
    },
})
export default class ComplianceRules extends Vue {
    Invest: any = new Invest();
    timeFormat = timeFormat;
    @Prop() indexClauseRelation; // 当前点击的条款
    @Prop() clauseCodesList; // 条款多选全部数据
    @Prop() treeNodeData;
    @Prop() indexClauseList; // 条款列表数据
    @Prop() checkItemIs; // 检查是否勾选条款有未复核
    // @Prop() indexClauseRelationList; // table数据
    copyEntryDialog: boolean = false;
    ruleQueryDialog: boolean = false;
    delConfirmationDialog: boolean = false;
    timeout = null; // 防抖
    itemCodes = []; // 多选
    indexClauseRelationParam = {
        clauseCode: '',
        entryNameOrCodeLike: '',
    }
    delType = {
        type: '',
        content: ''
    }; // 解除关联类型
    indexClauseRelationList = [];
    delContent: string = '是否解除当前关联关系？'
    layoutDialog: boolean = false; // 布局显示值
    showFieldList: any[] = []; // 要显示的表格列
    // 已选择字段列表
    selectedFieldList: any[] = [];
    fixedFieldList: any[] = [
        { content: '规则编号', id: 'entryCode', sortable: true },
    ];
    iconDom: any = null;
    tableKey: number = 0;
    calcLoading: boolean = false;
    entryTypeArr: any[] = []; // 风险类型
    // 全部表格列
    tableColumns: any[] = [
        { content: '规则编号', id: 'entryCode', sortable: true },
        { content: '规则说明', id: 'entryName', sortable: false, filters: [{ data: '' }], },
        { content: '变动序号', id: 'changeNo', sortable: false },
        { content: '规则类型', id: 'entryTypes', sortable: false },
        { content: '生效日期', id: 'beginDate', sortable: false },
        { content: '失效日期', id: 'endDate', sortable: false },
        { content: '优先级', id: 'level', sortable: false },
        { content: '状态', id: 'entryStatusValid', sortable: false },
        { content: '风险等级', id: 'controlGrade', sortable: false },
        { content: '条款来源', id: 'sourceType', sortable: false },
        { content: '作用范围', id: 'riskCalTypes', sortable: false },
        { content: '阈值类型1', id: 'thresholdType1', sortable: false },
        { content: '阈值1', id: 'thresholdValue1', sortable: false },
        { content: '阈值类型2', id: 'thresholdType2', sortable: false },
        { content: '阈值2', id: 'thresholdValue2', sortable: false },
        { content: '阈值类型3', id: 'thresholdType3', sortable: false },
        { content: '阈值3', id: 'thresholdValue3', sortable: false },
        { content: '比较方向', id: 'compareType', sortable: false },
        { content: '账户层次', id: 'originalAccountId', sortable: false },
        { content: '控制类型', id: 'accountControlType', sortable: false },
        { content: '控制账户', id: 'accountControlValue', sortable: false },
        { content: '排除账户', id: 'accountDebarValue', sortable: false },
        { content: '排除组', id: 'accountGroupDebarValue', sortable: false },
        { content: '修改日期', id: 'modifyDate', sortable: true, width: 180 },
        // { content: '修改时间', id: 'modifyTime', sortable: false },
        { content: '修改人', id: 'modifyUser', sortable: false },
        { content: '自定义分类', id: 'customType', sortable: false },
    ];
    mounted() {
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        this.queryLayout();
    }
    openRelevancyDialog() {
        for (let i = 0; i < this.clauseCodesList.length; i++) {
            if (this.clauseCodesList[i].modifyEvent == '1') {
                this.yh_message_warn('所选条款存在未复核！');
                return
            }
        }
        this.copyEntryDialog = true;
    }
    @Watch('indexClauseRelation.clauseCode', { immediate: true, deep: true })
    watchIndexClauseRelation(val) {
        this.indexClauseRelationParam.clauseCode = val;
        this.indexClauseRelationList = [];
        this.getIndexClauseRelationList(this.indexClauseRelationParam);
    }
    // 关联列表查询
    getIndexClauseRelationList(data) {
        this.indexClauseRelationList = [];
        this.itemCodes = [];
        this.$axios.post('/indexClauseRelation/list', {...data}).then((res: any) => {
            if (res.list) {
                res.list.forEach(item => this.indexClauseRelationList.push(item));
            }
            if (this.ruleQueryDialog == true) {
                this.yh_message_success('查询成功!')
            } 
            this.ruleQueryDialog = false;
        }); 
    }
    // 条款原文模糊搜索
    clauseTextLikeQuery(param) {
        this.debounce(this.fuzzyQuery, 500)
    }
    fuzzyQuery() {
        this.getIndexClauseRelationList(this.indexClauseRelationParam);
    }
    // 条目多选
    clauseChangeEvent(checked, row, rowIndex) {
        this.itemCodes = [];
        checked.selection.forEach(item => this.itemCodes.push(item));
    }
    // 点击高级查询btn
    clickRuleQuery() {
        this.ruleQueryDialog = true;
    }
    // 导出
    downLoadGroupFileBtn() {
        if (this.indexClauseRelationList.length == 0) {
            this.yh_message_warn('当前数据为空!');
            return
        }
        if (this.itemCodes.length > 0) {
            let data = [];
            this.itemCodes.forEach(item => {
                data.push(item.entryCode)
            })
            downLoadFile({
                url: '/indexClauseRelation/export',
                method: 'post',
                data: {
                    ...this.indexClauseRelationParam,
                    exportEntryCode: data
                },
            });
        } else if (this.itemCodes.length == 0) {
            downLoadFile({
                url: '/indexClauseRelation/export',
                method: 'post',
                data: {
                    ...this.indexClauseRelationParam,
                    exportEntryCode: []
                },
            });
        }
    }
    delClauseDialog(clauseCodes, param2) {
        if (this.itemCodes.length == 0 && param2 == '批量解除') {
            this.yh_message_warn('选择条目不可为空！');
            return
        }
        if (param2 == '批量解除' && this.checkItemIs == true) {
            this.yh_message_warn('存在未复核条款！');
            return
        }
        if (param2 == '单个解除' && this.indexClauseRelation.modifyEvent != undefined) {
            this.yh_message_warn('存在未复核条款！');
            return
        }
        this.delConfirmationDialog = true;
        this.delType.type = param2;
        if (param2 == '单个解除') {
            this.delType.content = clauseCodes.entryCode;
        } else {
            this.delType.content = '';
        }
    }
    // 关联条目
    emitCopyEntryDialog(param1, param2) {
        this.copyEntryDialog = param1;
        if (param2 == '确认关联') {
            this.getIndexClauseRelationList(this.indexClauseRelationParam);
            // this.$emit('emitComfirmRelation')
        }
    }
    // 解除关联
    handleRemoveRelations() {
        let data = [];
        if (this.delType.type == '批量解除') {
            this.itemCodes.forEach(item => {
                data.push({
                    clauseCode: this.indexClauseRelation.clauseCode,
                    entryCode: item.entryCode
                })
            })
        } else if (this.delType.type == '单个解除') {
            data.push({
                clauseCode: this.indexClauseRelation.clauseCode,
                entryCode: this.delType.content
            })
        }
        this.$axios.post('/indexClauseRelation/batchRemoveRelations', data).then((res: any) => {
            this.yh_message_success('解除关联成功！');
            this.delConfirmationDialog = false;
            this.getIndexClauseRelationList(this.indexClauseRelationParam);
        }).catch(() => {
            this.delConfirmationDialog = false;
        }); 
    }
    // 高级查询显示emit
    emitRuleQuery(param) {
        this.ruleQueryDialog = param;
    }
    // 高级查询确认
    emitConfirmQuery(param) {
        let data = param;
        data.clauseCode = this.indexClauseRelation.clauseCode;
        this.getIndexClauseRelationList(data);
    }
    // 删除确认窗口显示
    emitDialogVisible(param) {
        this.delConfirmationDialog = param;
    }
    // 删除确认窗口
    emitHandleBtn() {
        if (['批量解除', '单个解除'].includes(this.delType.type)) {
            this.handleRemoveRelations();
        }
    }
    // 防抖
    debounce(fun, time = 500) {
        if (this.timeout) {
            clearTimeout(this.timeout)
        }
        this.timeout = setTimeout(() => {
            fun()
        }, time);
    }
    filterChangeEvent() {}
    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }
        /* **************************** 布局设置start ***************************** */
    // 获取页面布局信息
    async queryLayout() {
        this.calcLoading = true;
        const resList: any = await new Promise((resolve, reject) => {
            getTableLayout('COMPLIANCE_RULES')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            this.calcLoading = false;
        } else {
            this.showFieldList = this.tableColumns;
            this.selectedFieldList = this.tableColumns;
            this.calcLoading = false;
        }
        // 重新渲染表格
        this.tableKey++;
        this.changeTable();
    }
    changeTable() {
        const _this = this;
        this.$nextTick(() => {
            let iconDom = (_this.$refs['upstreamTable'] as any).$el.querySelectorAll('.vxe-icon--funnel');
            for (let i:any = 0; i < iconDom.length; i++) {
                if (['规则说明'].includes(iconDom[i].parentNode.parentNode.children[0].innerHTML)) {
                    iconDom[i].className = 'vxe-filter--btn el-icon-search';
                }
            }
        });
    }
    // 转表格筛选下拉框数据
    objToArr(param) {
        const list = [];
        for (const key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }
    // 处理table中的数据
    getTablesData(data: any, props: any) {
        // 自定义风险分类
        let datas = data[props];
        if (props == 'entryTypes') {
            datas = data['entryType']
            return DictionConstUtil.EntryType[datas];
        } else if (props == 'entryStatusValid') {
            if (data[props] == true) {
                let span = '<span style="color:green">启用</span>';
                return span;
            } else {
                let span = '<span style="color:red">禁用</span>';
                return span;
            }
        } else if (props == 'sourceType') {
            return DictionConstUtil.SourceType[datas];
        } else if (props == 'beginDate') {
            if (datas == '0') {
                return '';
            } else {
                return datas;
            }
        } else if (props == 'endDate') {
            if (datas == '0') {
                return '';
            } else {
                return datas;
            }
        } else if (props == 'modifyDate') { 
            return datas + ' ' + timeFormat(data['modifyTime']);
        } else {
            return datas;
        }
    }
    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        const property = column['property'];
        return row[property].includes(option.data);
    }
    thresholdTypeFormat(value, unit): string {
        // 三目运算符, unit为'%'和'万元'、'万股'的由后端处理了，不由numberFormat方法处理
        return ['%', '万元', '万股'].includes(unit) ? value : numberFormat(value.replace(/[^0-9.]/gi, ''), unit) + unitShow(unit);
    }
}
</script>
<style lang="scss" scoped>
.operate {
    .operate-btn {
        // border: 1px solid green;
        width: 98%;
        display: flex;
        justify-content: space-between;
        margin: 10px auto;
    }
}
</style>
